package com.jay.media.music.ui.views

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.jay.media.music.ui.R
import kotlin.math.sqrt

/**
 * @author xuzhou4
 * @date 2022/1/11
 */
class MusicWaveView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet?,
    defStyleAttr: Int = 0,
    defStyleRes: Int = 0
) : View(context, attrs, defStyleAttr, defStyleRes) {

    private var drawing: Boolean = false
    private var mFloatArray: FloatArray = FloatArray(0)
    private var paint: Paint = Paint()

    private val cylinderWidth by lazy { width / sqrt(128 * 128 * 2F) }
    private val diff by lazy { resources.getDimensionPixelOffset(R.dimen.pluse_diff) }
    private val cylinderHeight by lazy { (width - diff) / mFloatArray.size / 2 }

    init {
        paint.color = Color.argb(0x80, 0x33, 0x33, 0x33)
        paint.isAntiAlias = true
    }

    @Synchronized
    fun updateFFTArray(floatArray: FloatArray) {
        this.mFloatArray = floatArray
        postInvalidate()
        drawing = true
    }

    @Synchronized
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas ?: return

        if (mFloatArray.isEmpty()) {
            drawing = false
            return
        }

        for ((i, j) in mFloatArray.withIndex()) {
            canvas.drawRect(
                cylinderWidth * i + diff * i,
                0f,
                cylinderWidth + cylinderWidth * i + diff * i,
                j * cylinderHeight,
                paint
            )
        }

        drawing = false
    }
}